/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-03-07 15:55:15
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:00:12
 */


'use strict';
define([
    '../../../../../modules/business/videoManage/base/baseView',
    '../../../../../modules/common/service',
    '../../../../framework/bean/admanage'
], function(
    BaseView,
    http
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;
        this.init = function(id, $chartWrapper,$table) {
            self.$el = $chartWrapper;
            self.render($chartWrapper,$table,id);
        }

        this.render = function($chartWrapper,$table,id) {
            $chartWrapper.find('.nav.nav-tabs-cus li.carousel').removeClass('active');
            $chartWrapper.find('.nav.nav-tabs-cus li.carousel:first').addClass('active');
            $table.off("TAB_SHOW").on("TAB_SHOW",function(e){//处理图表或者其他。。
                e.stopImmediatePropagation();
                var da = e.originalEvent.data; // 返回数据如下
                self.appendSelectDom(da.GD,id);
                self.showChart(da.index,'7',da.GD, id);
            });
            setTimeout(function() {
                var _$chartOutDom = $chartWrapper.find("div.active[role='tabpanel']");
                self.appendSelectDom(_$chartOutDom,id);
                self.showChart(0,'7',_$chartOutDom, id);
            },400)
        }

        this.appendSelectDom = function(_$chartOutDom,id) {
            _$chartOutDom.find("div.ndp-drop-wrapper[name=inline-drop]").remove();
            var _dorpDom = $('<div class="ndp-drop-wrapper" name="inline-drop"/>').appendTo(_$chartOutDom);
            _dorpDom.drop({
                data: [{name : window.I18N.getText('management','dateRanges7'), val : '7'},
                    {name : window.I18N.getText('management','dateRanges30'), val : '30'},
                    {name : window.I18N.getText('management','dateRanges90'), val : '90'}]
            }).val({name : window.I18N.getText('management','dateRanges7'), val : '7'});
            _dorpDom.off("ITEM_CLICK").on("ITEM_CLICK", function (e) {
                //下拉选择项点击事件
                //返回的数据有  {val:选中项的值,deep:深度(如果是多级) }
                var index = $(this).closest(".chart-wrapper").find("ul li.active").data("index");
                self.showChart(index,e.originalEvent.data.val,_$chartOutDom,id);
            });
        }
        /**
         * 渲染 chart
         * @param index tab index
         * @param dateVal drop中当前值
         */
        this.showChart = function(index, dateVal, _$chartOutDom,id) {
            _$chartOutDom.find("div[name=adchart-dom]").remove();
            var _dom = $('<div name="adchart-dom" style="height: 90%;"/>').appendTo(_$chartOutDom);
            var _json;
            http.do("/common/timestamp", {param: JSON.stringify({})}).then(function(dateResult) {
                if (index == 0) {
                    // Result & Cost 双轴线
                    _json = window.twoYAxis;
                } else if (index == 1) {
                    //CRT 单轴线
                    _json = window.twoYAxis;
                }
                _json.data[0].rows = [];
                var today = moment(dateResult.data.date).utcOffset(window.sessionStorage.timezoneValue)
                    .subtract(0, 'days').format('YYYY-MM-DD');
                var until,days;
                if (dateVal == "7") {
                    //前七天
                    days = 7;
                    _json.data[0].fields[0].unit = "timestamp";
                    until = moment(dateResult.data.date).utcOffset(window.sessionStorage.timezoneValue)
                        .subtract(6, 'days').format('YYYY-MM-DD');
                } else if (dateVal == "30") {
                    days = 30;
                    _json.data[0].fields[0].unit = "timestamp";
                    until = moment(dateResult.data.date).utcOffset(window.sessionStorage.timezoneValue).subtract(29, 'days').format('YYYY-MM-DD');
                } else if (dateVal == "90") {
                    days = 90;
                    _json.data[0].fields[0].unit = "week";
                    until = moment(dateResult.data.date).utcOffset(window.sessionStorage.timezoneValue).subtract(89, 'days').format('YYYY-MM-DD');
                }
                var arr = getTimeStemp(days,dateResult.data.date);
                http.do("/admanage/graphbyday", {param: JSON.stringify({
                    "ecReport" : true,
                    "id": id,
                    "statsTimeRange": {
                        "since": until,
                        "until": today
                    },
                    "returnStatsFields": index == 0?["purchase", "cpc"]:["roi", "salesAmount"]})
                }).then(function(res) {
                    _hide('.fmp-monitor');
                    var _data = res.data;
                    //构造rows
                    if (index == 0) {
                        _json.data[0].fields[1].name = "CPC ($)";
                        _json.data[0].fields[1].format.numericDecimals = 2;
                        _json.data[0].fields[2].name = "Purchase";
                        //修改data数据
                        for (var i = 0; i < arr.length; i++) {
                            var tempArr = [];
                            tempArr.push(arr[i]);
                            tempArr.push(_data.cpc[i] / 100);
                            tempArr.push(_data.purchase[i] * 1.0);
                            //if(i == arr.length - 1){
                            //    tempArr.push(1);
                            //}else{
                            //    tempArr.push(0);
                            //}
                            //tempArr.push(_data.cpc[i]/100);
                            //tempArr.push(_data.purchase[i]*1.0);
                            _json.data[0].rows.push(tempArr);
                        }
                    } else if (index == 1) {
                        _json.data[0].fields[1].name = "SalesAmount ($)";
                        _json.data[0].fields[1].format.numericDecimals = 2;
                        _json.data[0].fields[2].name = "ROI";
                        _json.data[0].fields[2].format.numericDecimals = 2;
                        //修改data数据
                        for (var i = 0; i < arr.length; i++) {
                            var tempArr = [];
                            tempArr.push(arr[i]);
                            tempArr.push(_data.salesAmount[i] / 100);
                            tempArr.push(_data.roi[i]);
                            if(i == arr.length - 1){
                                tempArr.push(1);
                            }else{
                                tempArr.push(0);
                            }
                            tempArr.push(_data.salesAmount[i] / 100);
                            tempArr.push(_data.roi[i]);
                            _json.data[0].rows.push(tempArr);
                        }
                    }
                    var chartWidget = new ChartWidget();
                    var eventListener = new ChartEventListener();
                    chartWidget.addEventListener(eventListener);
                    chartWidget.placeAt(_dom);
                    chartWidget.setVisJson(_json);
                    // $('[name=ad-chart]').css('width',$('.monitor-table').width()-190+'px')
                }, function() {});
            }, function() {});
        }

        function getTimeStemp(days,date) {
            var arr = [];
            for (var i = 0; i < days; i++) {
                var t = moment(moment(date).utcOffset(window.sessionStorage.timezoneValue)
                    .subtract(days - i - 1, 'days').format('YYYY-MM-DD')).valueOf();
                arr.push(t)
            }
            return arr;
        }

        function _hide(dom) {
            if (!dom) {
                var dom = 'html';
            }
            dom = $(dom);
            var loading = dom.find('> .load-area');
            if (dom[0] && dom[0].nodeName == 'TR') {
                loading = $('body').find('> .load-area');
            }
            loading.fadeOut(500, function() {
                dom.css('position', dom.attr('original') || '')
                $(this).remove();
            })
        }

    };
    return me;
});
